<!--
 * @Date: 2025-09-07 21:10:46
 * @LastEditors: 贾二小 erxiao.jia@outlook.com
 * @LastEditTime: 2025-11-19 17:13:06
 * @FilePath: /admin-vue/src/views/admin/system/role/modules/role-operate-modal.vue
-->
<script setup lang="ts">
import { $t } from '@/locales'
import type { FormInst, FormRules } from 'naive-ui'

defineOptions({ name: 'RoleOperateModal' })

const { find, add, update } = useRole()
const { loading: loading, startLoading, endLoading } = useLoading(false)

interface Props {
  visible: boolean
  type?: 'add' | 'edit'
  id?: number
  load: Function
}

interface Emits {
  (e: 'update:visible', visible: boolean): void
  (e: 'load'): void
}

const emit = defineEmits<Emits>()
const props = withDefaults(defineProps<Props>(), {
  type: 'add',
})

const defaultModel = (): RoleModel => ({ name: '', description: '' })

const formModel = ref<RoleModel>(defaultModel())

const formRef = ref<FormInst | null>(null)

watch(
  () => props.visible,
  async (newValue) => {
    if (newValue) {
      if (props.type === 'edit' && props.id) {
        formModel.value = await find(props.id)
      }
    }
  },
)

const modalTitle = computed(() => {
  const titles: Record<'add' | 'edit', string> = {
    add: $t('page.system.role.addRole'),
    edit: $t('page.system.role.editRole'),
  }
  return titles[props.type]
})

const rules: FormRules = {
  name: {
    required: true,
    message: $t('page.system.role.namePlaceholder'),
    trigger: 'input',
  },
  description: {
    required: true,
    message: $t('page.system.role.descriptionPlaceholder'),
    trigger: 'input',
  },
}

const handleModalConfirm = async () => {
  // 表单验证
  const valid = await formRef.value?.validate((errors) => !errors)
  if (!valid) return

  startLoading()
  try {
    // 调用新增/编辑接口
    const { success } =
      props.type === 'add' ? await add(formModel.value) : await update(formModel.value)

    // 接口调用成功后，刷新表格数据
    if (success) {
      handleModalClose(false)
      emit('load')
    }
  } finally {
    endLoading()
  }
}

const handleModalClose = (visible: boolean) => {
  emit('update:visible', visible)
}
</script>

<template>
  <ad-modal
    :visible="visible"
    :title="modalTitle"
    :loading="loading"
    @update:visible="handleModalClose"
    @confirm="handleModalConfirm"
    class="max-w-md"
  >
    <n-form ref="formRef" :label-width="80" :model="formModel" :rules="rules">
      <n-form-item :label="$t('page.system.role.name')" path="name">
        <n-input
          v-model:value="formModel.name"
          :placeholder="$t('page.system.role.namePlaceholder')"
        />
      </n-form-item>
      <n-form-item :label="$t('page.system.role.description')" path="description">
        <n-input
          type="textarea"
          v-model:value="formModel.description"
          :placeholder="$t('page.system.role.descriptionPlaceholder')"
          rows="3"
        />
      </n-form-item>
    </n-form>
  </ad-modal>
</template>

<style lang="scss" scoped></style>
